<?php

namespace app\api\controller;

use AlibabaCloud\Client\AlibabaCloud;
use app\common\controller\Api;
use app\common\facade\EsClient;
use app\common\library\aliyuns\MtsClient;
use app\common\library\aliyuns\VideoClient;
use app\job\queue\Job1;
use app\logic\es\EsUser;
use app\logic\es\fp\EsPost;
use app\Request;
use Elastic\Elasticsearch\Exception\ClientResponseException;
use Elastic\Elasticsearch\Exception\MissingParameterException;
use Elastic\Elasticsearch\Exception\ServerResponseException;
use think\App;

use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\facade\Queue;

use Overtrue\Socialite\SocialiteManager;

class Test extends Api
{
    public function __construct(App $app)
    {
        parent::__construct($app);

        //正式服不给调用测试接口
        if (config('app.env') == 'prod') {
            $this->error('非法请求');
        }
    }

    public function es()
    {
        $data = $this->request->param();
        try {
            $res = EsPost::getInstance()->import($data);
        } catch (\Throwable $e) {
            var_dump($e->getMessage() . PHP_EOL . $e->getTraceAsString());
        }


        var_dump($res);
    }

    public function es_del_index()
    {
        $index = $this->request->param('index');

        try {
            $res = EsPost::getInstance()->deleteIndex();
        } catch (ClientResponseException $e) {
            var_dump($e->getResponse()->getStatusCode());
        } catch (MissingParameterException $e) {
        } catch (ServerResponseException $e) {
        }


    }

    public function es_query()
    {
        $params = $this->request->param(['query', 'from', 'size']);

        try {
            // 执行搜索
            $response = EsPost::getInstance()->query($params);
            var_dump($response->asArray());
//            // 输出结果
//            foreach ($response['hits']['hits'] as $hit) {
//                echo "ID: " . $hit['_id'] . "\n";
//                echo "Source: " . json_encode($hit['_source'], JSON_UNESCAPED_UNICODE) . "\n";
//
//                // 输出高亮部分
//                if (isset($hit['highlight'])) {
//                    foreach ($hit['highlight'] as $field => $highlightedText) {
//                        echo "Highlighted $field: " . implode(' ', $highlightedText) . "\n";
//                    }
//                }
//            }
        } catch (\Throwable $e) {
            var_dump($e->getMessage() . PHP_EOL . $e->getTraceAsString());
        }

        exit;
    }

    public function google(Request $request)
    {

        $config = config('socialite');

        $socialite = new SocialiteManager($config);

        $url = $socialite->create('google')->redirect();

        return redirect($url);
    }

    public function facebook(Request $request)
    {


        $config = config('socialite');

        $socialite = new SocialiteManager($config);

        $url = $socialite->create('facebook')->redirect();

        return redirect($url);
    }

    public function callback(Request $request)
    {

        $platform = $request->get('pl');
        $code = $request->get('code');

        $config = config('socialite');
        $socialite = new SocialiteManager($config);

        try {
            $user = $socialite->create($platform)->userFromCode($code);
            dump($user);
        } catch (\Exception $exception) {
            var_dump($exception->getMessage());
        }


    }

    public function queue(Request $request)
    {

        /* {
                "data": {
                    "name": "toney2",
                    "message": "hi"
                },
                "queue": "chat"
            }
         */
        $data = $request->param('data');
        $queue = $request->param('queue');
        $id = Queue::push(Job1::class, $data, $queue);
        var_dump($id);
    }


    public function snapshotJob()
    {
        $inputUrl = 'storage/default/20240924-160939.mp4';

        $outPutUrl = 'storage/default/snapshot/output/{Count}.jpg';

        $videoClient = new MtsClient();

        $info = $videoClient->snapshotJobAsync($inputUrl, $outPutUrl, 0, 20);

//        $cover = $info['SnapshotJob']['SnapshotConfig']['OutputFile']['Object'];
        echo json_encode($info);
    }

    public function querySnapshotJob()
    {
        $jobId = $this->request->param('jobId');

        $videoClient = new MtsClient();

        $info = $videoClient->querySnapshotJob($jobId);


        echo json_encode($info, 256);
    }

    public function videoTransfer()
    {

        $inputUrl = 'storage/default/20240924-160939.mp4';
        $outPutUrl = 'storage/default/snapshot/output/20241219-001_{Count}.jpg';

        $videoClient = new MtsClient();

        $info = $videoClient->snapshotJob($inputUrl, $outPutUrl, 1);


        var_dump($info);
    }

    public function get()
    {

        $inputUrl = 'storage/default/20241218/%E9%A3%9E%E4%B9%A620240924-160924030cc11e4254634c81dd3de828d6e5358ef7b5.mp4';
        $outPutUrl = 'storage/default/snapshot/output/20241219-001_{Count}.jpg';

        $videoClient = new MtsClient();

        $info = $videoClient->snapshotJob($inputUrl, $outPutUrl, 1);


        var_dump($info);
    }


    public function userImport()
    {
        $type = $this->request->param('type');
        $type = $type ?: 'all';
        try {
            switch ($type) {
                case 'all':
                    EsUser::getInstance()->deleteIndex();
                  //  EsUser::getInstance()->importAll();
                    break;
                default:
                    $uid = $this->request->param('uid');
                    if (!$uid) {
                        $this->error('请输入uid');
                    }
                    EsUser::getInstance()->import($uid);
                    break;
            }
        } catch (\Throwable $e) {
            var_dump($e->getMessage() . PHP_EOL . $e->getTraceAsString());
        }


        $this->success('导入成功');
    }

    public function esPostDel()
    {
        $id = $this->request->param('id');
        try {
            $res = EsPost::getInstance()->delete($id);
        } catch (\Throwable $e) {
            var_dump($e->getMessage() . PHP_EOL . $e->getTraceAsString());
        }

        $this->success('删除成功');
    }
    public function esUserIndexDel()
    {
        try {
            $res = EsUser::getInstance()->deleteIndex();
        } catch (\Throwable $e) {
            var_dump($e->getMessage() . PHP_EOL . $e->getTraceAsString());
        }

        $this->success('删除成功');
    }

    // 发系统消息DEMO
    public function sendSystemNotifyDemo()
    {
        $result = \app\logic\system\NotifyLogic::getInstance()->pushMessage(
            \app\common\enum\SystemNotifyTypeEnum::NEW_POST->value,
            [2, 23, 26],
            '残鸡英发布新动态啦',
            '食烟饮酒讲粗口，哒哒哒哒哒'
        );

        $this->success('发送成功', [$result]);
    }

    public function crateEsApiKey()
    {
        try {
            $res = EsUser::getInstance()->apiKey();
        } catch (ClientResponseException|MissingParameterException|ServerResponseException $e) {
            $this->error('创建失败', $e->getMessage());
        }
        $this->success('创建成功', $res->asArray());
    }

    public function esanalyze()
    {
        try {
            $index = $this->request->param('index');
            $body = $this->request->param('body');
            $res = EsUser::getInstance()->analyze($index, $body);
        } catch (ClientResponseException|ServerResponseException $e) {
            $this->error('分析失败', $e->getMessage());
        }
        $this->success('分析成功', $res->asArray());
    }
    public function esplugins()
    {
        try {
            $params = $this->request->param('params');
            $res = EsUser::getInstance()->plugins($params);
        } catch (ClientResponseException|ServerResponseException $e) {
            $this->error('获取失败', $e->getMessage());
        }
        $this->success('获取成功', $res->asString());
    }
}